package com.uroad.jilinpda.widget;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.uroad.jilinpda.BuildConfig;
import com.uroad.jilinpda.R;
import com.uroad.jilinpda.modle.PlateColorMDL;
import com.uroad.jilinpda.util.ImageUtils;
import com.uroad.jilinpda.util.KeyboardUtil;
import com.uroad.jilinpda.util.RegularUtil;
import com.uroad.jilinpda.util.ToastUtil;
import com.uroad.lib.util.check.CheckPermissionUtil;
import com.uroad.lib.util.sys.SystemUtil;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChoosePlateColorDialog extends AlertDialog {
    private static final int STATUS_INPUT = 0;//输入状态
    private static final int STATUS_COMPLETE = 1;//输入完成状态
    private static final int STATUS_MODIFY = 2;//修改状态

    private int curStatus = STATUS_INPUT;
    private Activity context;
    private OnDatePickerListener onDatePickerListener;
    int position;
    private TextView tvTrips;
    private EditText tv_plate1;
    private EditText tv_plate2, tv_plate3, tv_plate4, tv_plate5, tv_plate6, tv_plate7, tv_plate8;
    private List<EditText> mEdits = new ArrayList<EditText>();
    private EditText selectEdit;
    private RecyclerView rc_carplat_color;
    private ImageView iv_plat_add;
    private PlatColorAdapter adapter;
    private SelectProvincePop pop;
    private TextView tv_confirm;
    private EditText et_code;
    private TextView tv_cartype_bus, tv_cartype_freight,tv_cancelYes,tv_cancelNo;
    private TextView tv_cartype;
    private ImageView tv_photo;
    private LinearLayout ll_cartype;
    private LinearLayout line_code;
    private KeyboardUtil keyboardUtil;
    private View view;
    private OnSelectVehtypeListener selectVehtype;
    private OnSelectCancleListener selectCancle;
    private TextView tv_combodesc;
    private boolean isSelectPlat = false;
    private String flagNew;
    private String worknumber;
    /**车牌是否输入完成 完成后点击则只修改当前edittext*/
    private boolean isPlateInputConfirm = false;
    private String etCode="";
    private boolean flagCode=true;
    private List<PlateColorMDL> plateColorMDL;
    CheckPermissionUtil checkPermissionUtil;
    private String mFilePath;
    private String way;
    private File mCurrentPhotoFile;
    private String numberPlat = "";
    private String platColor="";
    private View view_no;
    private LinearLayout line_noShow;
    private boolean isGreenPlat = false;//是否选择了新能源车牌
    private static final int TAKE_PICTURE = 0x000008;
    private boolean flagHasPlate=true;
    private static final File PHOTO_DIR = new File(Environment
            .getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera");
    public ChoosePlateColorDialog(Context context, String flag, String workNumber) {
        super(context, R.style.AppDialog);
        this.context = (Activity) context;
        flagNew=flag;
        worknumber=workNumber;
        setCanceledOnTouchOutside(true);
        setCancelable(true);
    }
    public void setCombodesc(String combodesc){
        tv_combodesc.setText(combodesc);
    }
    public ChoosePlateColorDialog setList(ArrayList<String> list) {
        return this;
    }
    public ChoosePlateColorDialog setOnDatePickerListener(OnDatePickerListener onDatePickerListener) {
        this.onDatePickerListener = onDatePickerListener;
        return this;
    }

    public void setPlateColor(List<PlateColorMDL> plateColorMDL){
        this.plateColorMDL = plateColorMDL;
    }

    @Override
    public void show() {
        super.show();
        Window window = getWindow();
        if (window != null) {
            View view = null;
            if (flagNew.equals("2")||flagNew.equals("3")){
                view = LayoutInflater.from(context).inflate(R.layout.dialog_plateobu_colorpicker1, null);
            }else if(flagNew.equals("1")){
                flagHasPlate=false;
                view = LayoutInflater.from(context).inflate(R.layout.dialog_plate_colorpicker1, null);
            }
            window.setContentView(view);
            this.view = view;
            initView(view);
            window.setLayout(SystemUtil.getScreenWidth(context), WindowManager.LayoutParams.WRAP_CONTENT);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.Animation_Bottom_Rising);
            window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }
    }
    private void initView(View view) {
        TextView tv_cancel = (TextView)view.findViewById(R.id.tv_cancel);
        line_code = (LinearLayout) view.findViewById(R.id.line_code);
        tv_combodesc = (TextView)view.findViewById(R.id.tv_combodesc);
        et_code = (EditText) view.findViewById(R.id.et_code);
        tv_photo = (ImageView)view.findViewById(R.id.tv_photo);
        view_no = (View) view.findViewById(R.id.view_no);
        line_noShow = (LinearLayout) view.findViewById(R.id.line_noShow);
        tv_confirm = (TextView)view.findViewById(R.id.tv_confirm);
        tv_plate1 = (EditText) view.findViewById(R.id.tv_plate1);
        tv_plate2 = (EditText) view.findViewById(R.id.tv_plate2);
        tv_plate3 = (EditText) view.findViewById(R.id.tv_plate3);
        tv_plate4 = (EditText) view.findViewById(R.id.tv_plate4);
        tv_plate5 = (EditText) view.findViewById(R.id.tv_plate5);
        tv_plate6 = (EditText) view.findViewById(R.id.tv_plate6);
        tv_plate7 = (EditText) view.findViewById(R.id.tv_plate7);
        tv_plate8 = (EditText) view.findViewById(R.id.tv_plate8);
        tv_cartype_bus = (TextView) view.findViewById(R.id.tv_cartype_bus);
        tv_cartype_freight = (TextView) view.findViewById(R.id.tv_cartype_freight);
        tv_cancelYes = (TextView) view.findViewById(R.id.tv_cancelYes);
        tv_cancelNo = (TextView) view.findViewById(R.id.tv_cancelNo);
        rc_carplat_color = (RecyclerView) view.findViewById(R.id.rc_carplat_color);
        iv_plat_add = (ImageView) view.findViewById(R.id.iv_plat_add);
        tvTrips = (TextView) view.findViewById(R.id.tvTrips);
        if ("3".equals(flagNew)){
            tv_confirm.setText("确定");
        }
        if (worknumber.equals("1")&&flagNew.equals("1")){
            line_code.setVisibility(View.GONE);
        }else if (worknumber.equals("2")){
            line_code.setVisibility(View.GONE);
        }
        //        String html="<html><head><title>TextView使用HTML</title></head><body><p><strong>强调</strong></p><p><em>斜体</em></p>"
        //                +"<p><a href=\"http://www.dreamdu.com/xhtml/\">超链接HTML入门</a>学习HTML!</p><p><font color=\"#aabb00\">颜色1"
        //                +"</p><p><font color=\"#00bbaa\">颜色2</p><h1>标题1</h1><h3>标题2</h3><h6>标题3</h6><p>大于>小于<</p><p>" +
        //                "下面是网络图片</p><img src=\"http://avatar.csdn.net/0/3/8/2_zhang957411207.jpg\"/></body></html>";
        tvTrips.setText(Html.fromHtml("请选择<font color='#3F51B5'><strong>车牌颜色</strong></font>"));
        mEdits.add(tv_plate1);
        mEdits.add(tv_plate2);
        mEdits.add(tv_plate3);
        mEdits.add(tv_plate4);
        mEdits.add(tv_plate5);
        mEdits.add(tv_plate6);
        mEdits.add(tv_plate7);
        //        mEdits.add(tv_plate8);
        //        tv_plate2.setFocusable(true);
        checkPermissionUtil = new CheckPermissionUtil(context, new String[]{
                Manifest.permission.CAMERA}, new CheckPermissionUtil.CheckPermissionCallBack() {
            @Override
            public void permissionAllow() {
                if (way.equals("camera"))
                    takePhoto();
                else if (way.equals("pic"))
                    goPhotoAlbum();
            }

            @Override
            public void permissionRefuse() {

            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        /*if (ETCDealInfoMDL.getInstance().getOrderMDL().getIscar().equals("1")&&
                ETCDealInfoMDL.getInstance().getOrderMDL().getIstrucks().equals("1") ){
            tv_cartype.setVisibility(View.VISIBLE);
            ll_cartype.setVisibility(View.VISIBLE);
        }else if(ETCDealInfoMDL.getInstance().getOrderMDL().getIscar().equals("1")&&
                ETCDealInfoMDL.getInstance().getOrderMDL().getIstrucks().equals("0") ){
            vehtype = "1";
        }else if(ETCDealInfoMDL.getInstance().getOrderMDL().getIscar().equals("0")&&
                ETCDealInfoMDL.getInstance().getOrderMDL().getIstrucks().equals("1") ){
            vehtype = "2";
        }*/
        setListener();
        if (tv_photo != null) {
            tv_photo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openCarme();
                }
            });
        }
    }

    public String getmFilePath() {
        return mFilePath == null ? "" : mFilePath;
    }

    public void setNumberPlat(String numberPlat) {
        flagHasPlate=true;
        tv_confirm.setClickable(true);
        view_no.setVisibility(View.GONE);
        line_noShow.setVisibility(View.VISIBLE);
       // tv_photo.setClickable(false);
        this.numberPlat = numberPlat;//车牌
        //关闭软键盘
        keyboardUtil.hideKeyboard();
        if (numberPlat.length() < 7) {
            return;
        }
        //省填上
        String[] plat = numberPlat.split("");
        if (plat.length > 8) {
            //新能源
            addEdit();
        }else{
            //正常牌
            delEdit();
        }
        for (int i = 0; i < mEdits.size(); i++) {
            mEdits.get(i).setText(plat[i+1]);
        }

    }
    public void setPlateImage(String plateImage) {
        ImageUtils.ShowPic2View(context, plateImage, tv_photo);

    }

    public void setPlatColor(String platColor) {
        this.platColor = platColor;//颜色
        if (!TextUtils.isEmpty(platColor)) {
            for (int i = 0; i < plateColorMDL.size(); i++) {
                PlateColorMDL colorMdl = plateColorMDL.get(i);
                if (platColor.equals(colorMdl.getDictcode())) {
                    if (isFinish())
                        tv_confirm.setBackgroundResource(R.color.main_blue);
                    else
                        tv_confirm.setBackgroundResource(R.color.etcplatcolor);
                    setSelect(i);
                    return;
                }
            }
            //清空
            clearPlatColor();
        }else{
            tv_confirm.setBackgroundResource(R.color.etcplatcolor);
            //清空
            clearPlatColor();
        }
    }

    private void clearPlatColor() {
        isSelectPlat = false;
        adapter.notifyDataSetChanged();
    }

    private void setSelect(int i) {
        isSelectPlat = true;
        adapter.setPos(i);
        adapter.notifyDataSetChanged();
    }

    //跳转拍照
    private void takePhoto() {
        try {
            PHOTO_DIR.mkdirs();
            // 保存图片的文件名
            String fileName = String.valueOf(System.currentTimeMillis());
            mFilePath = PHOTO_DIR + fileName + ".jpg";
            mCurrentPhotoFile = new File(mFilePath);
            if (!mCurrentPhotoFile.exists()) {
                try {
                    mCurrentPhotoFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = getTakePickIntent(mCurrentPhotoFile);
            context.startActivityForResult(intent, TAKE_PICTURE);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(context, "无法启用拍照功能", Toast.LENGTH_LONG).show();
        }
   /*     String fileName = String.valueOf(System.currentTimeMillis());
        mFilePath = Environment.getExternalStorageDirectory().getPath();
        // 保存图片的文件名
        mFilePath = mFilePath + "/Photo_Report/" + fileName + ".jpg";
        // 指定拍照意图
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 加载路径图片路径
        Uri mUri = Uri.fromFile(new File(mFilePath));
        // 指定存储路径，这样就可以保存原图了
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);*/
        //        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //        startActivityForResult(openCameraIntent, TAKE_PICTURE);

    }
    //激活相册操作
    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        context.startActivityForResult(intent, 2);
    }
    public Intent getTakePickIntent(File f) {
        Uri photoUri;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            photoUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", f);
        } else {
            photoUri = Uri.fromFile(f);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                photoUri);
        intent.putExtra("return-data", false);
        return intent;
    }
    private void openCarme() {
        SYSDiaLogUtils.showConfirmPhotoDialog(context, new SYSDiaLogUtils.ConfirmDialogListener() {
            @Override
            public void onClickButton(boolean clickLeft, boolean clickRight) {
                if (clickLeft) {
                    way = "camera";
                    checkPermissionUtil.checkPermissions();
                } else if (clickRight) {
                    way = "pic";
                    checkPermissionUtil.checkPermissions();
                }
            }
        });
    }
    private void setListener(){
        tv_plate2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pop != null && pop.isShowing()) {
                    pop.dismiss();
                }
            }
        });
        tv_cartype_bus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_cartype_bus.setBackgroundResource(R.drawable.bg_shape_buleline);
                tv_cartype_bus.setTextColor(Color.parseColor("#FF0247B3"));
                tv_cartype_freight.setBackgroundResource(R.drawable.bg_shape_grayline);
                tv_cartype_freight.setTextColor(Color.parseColor("#999999"));
                if (selectVehtype != null) {
                    selectVehtype.onVehtype("1");
                }
            }
        });
        tv_cartype_freight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_cartype_freight.setBackgroundResource(R.drawable.bg_shape_buleline);
                tv_cartype_freight.setTextColor(Color.parseColor("#FF0247B3"));
                tv_cartype_bus.setBackgroundResource(R.drawable.bg_shape_grayline);
                tv_cartype_bus.setTextColor(Color.parseColor("#999999"));
                if (selectVehtype != null) {
                    selectVehtype.onVehtype("2");
                }
            }
        });
        tv_cancelYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_cancelYes.setBackgroundResource(R.drawable.bg_shape_buleline);
                tv_cancelYes.setTextColor(Color.parseColor("#FF0247B3"));
                tv_cancelNo.setBackgroundResource(R.drawable.bg_shape_grayline);
                tv_cancelNo.setTextColor(Color.parseColor("#999999"));
                if (selectCancle != null) {
                    selectCancle.onCancle("1");
                }
            }
        });
        tv_cancelNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_cancelNo.setBackgroundResource(R.drawable.bg_shape_buleline);
                tv_cancelNo.setTextColor(Color.parseColor("#FF0247B3"));
                tv_cancelYes.setBackgroundResource(R.drawable.bg_shape_grayline);
                tv_cancelYes.setTextColor(Color.parseColor("#999999"));
                if (selectCancle != null) {
                    selectCancle.onCancle("0");
                }
            }
        });
        for (int i=0;i<mEdits.size();i++){
            final EditText et = mEdits.get(i);
            et.addTextChangedListener(new MyTextWatcher());
            //            et.setOnFocusChangeListener(this);
            //            et.setOnKeyListener(this);
            et.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            et .setImeOptions(EditorInfo.IME_ACTION_DONE);
            et.setTransformationMethod(new TransInformation());
            int finalI = i;
            et.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view1, MotionEvent motionEvent) {
//                    if (curStatus == STATUS_COMPLETE) {//完成状态
                        curStatus = STATUS_MODIFY;//修改状态
                        setBackground(et);
                        selectEdit = et;
                        et.setText("");
//                        keyboardUtil.setHideKeyboardEnable(false);//不能关闭软键盘
//                        if (finalI != mEdits.size() - 1) {
//                            keyboardUtil.setDeleteEnable(false);//不能删除
//                        }
//                    }else{
//                        focus("click");
//                    }
                    return false;
                }
            });
        }
        /*et_code.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // TODO Auto-generated method stub
                String key = s.toString();
                if (key.length() > 0&&key.length()<=7) {
                    flagCode = false;
                    tv_confirm.setBackgroundResource(R.color.main_light_blue);
                } else {
                    flagCode = true;
                    if (isFinish()&&isSelectPlat)
                        tv_confirm.setBackgroundResource(R.color.main_blue);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });*/
        iv_plat_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view1) {
                if(flagNew.equals("1")){
                    isSelectPlat = false;
                }else if ((flagNew.equals("2")||flagNew.equals("3"))){
                    isSelectPlat=true;
                }
                adapter.setPos();
                addEdit();
                if (isFinish()&&isSelectPlat)
                    tv_confirm.setBackgroundResource(R.color.main_blue);
                else
                    tv_confirm.setBackgroundResource(R.color.etcplatcolor);
            }
        });

        adapter = new PlatColorAdapter(context, plateColorMDL);
        //设置布局管理器
        rc_carplat_color.setLayoutManager(new GridLayoutManager(context,4));
        rc_carplat_color.setAdapter(adapter);
        //        adapter.setPos(0);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(flagNew)&&!flagHasPlate){
                    return;
                }
                etCode = et_code.getText().toString().trim();
                if (!isSelectPlat)
                    ToastUtil.show(context,"请选择车牌颜色");
                else if (!isFinish()){
                    ToastUtil.show(context,"请将车牌号码输入完整");
                }else{
                    getResponse();
                }
            }
        });
        focus("click");//默认直接弹出键盘
        tv_plate1.setText("吉");
    }

    private void setBackground(EditText et) {
        for (int i = 0; i < mEdits.size(); i++) {
            if (i == 0) {
                if (et!=null&&et == mEdits.get(i)) {
                    et.setBackgroundResource(R.drawable.bg_shape_main_blue_left);
                }else {
                    mEdits.get(i).setBackgroundResource(R.drawable.bg_shape_grayline_left);
                }
            } else if (i == 1) {
                if (et!=null&&et == mEdits.get(i)) {
                    et.setBackgroundResource(R.drawable.bg_shape_main_blue_right);
                }else {
                    mEdits.get(i).setBackgroundResource(R.drawable.bg_shape_grayline_right);
                }
            }else{
                if (et!=null&&et == mEdits.get(i)) {
                    et.setBackgroundResource(R.drawable.bg_shape_main_blue);
                }else {
                    mEdits.get(i).setBackgroundResource(R.drawable.bg_shape_grayline);
                }
            }
        }
    }

    private boolean isFinish(){
        for (EditText ed: mEdits){
            if (ed.getText().length()<1)
                return false;
        }
        return true;
    }
    private void addEdit(){
        if (mEdits.size() < 8){
            iv_plat_add.setVisibility(View.GONE);
            tv_plate8.setVisibility(View.VISIBLE);
            mEdits.add(tv_plate8);
            tv_plate8.addTextChangedListener(new MyTextWatcher());
            //        tv_plate8.setOnFocusChangeListener(ChoosePlateColorDialog.this);
            //        tv_plate8.setOnKeyListener(ChoosePlateColorDialog.this);
            tv_plate8.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            tv_plate8 .setImeOptions(EditorInfo.IME_ACTION_DONE);
            tv_plate8.setTransformationMethod(new TransInformation());
            tv_plate8.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view1, MotionEvent motionEvent) {
                    setEndEditFocus();
                    return false;
                }
            });
            setEndEditFocus();
        }
    }

    private void setEndEditFocus() {
//        if (curStatus == STATUS_COMPLETE) {
            curStatus = STATUS_MODIFY;//修改状态
            setBackground(tv_plate8);
            selectEdit = tv_plate8;
            tv_plate8.setText("");
//            keyboardUtil.setHideKeyboardEnable(false);//不能关闭软键盘
//            keyboardUtil.setDeleteEnable(false);//不能删除
//        }else {
//            focus("click");//直接弹出键盘
//        }
    }

    private void delEdit(){
        iv_plat_add.setVisibility(View.VISIBLE);
        tv_plate8.setVisibility(View.GONE);
        if (mEdits.size() == 8)
            mEdits.remove(7);
    }
    /* private void showPop() {
         if (pop == null) {
             pop = new SelectProvincePop(context);
         }
         pop.setSelectProvince(new SelectProvincePop.onSelectProvince() {
             @Override
             public void onSelect(String province) {
                 tv_plate1.setText(province);
             }
             @Override
             public void onCancel() {
             }
         });
         pop.getContentView().measure(0, 0);
         int height = pop.getContentView().getMeasuredHeight();
         pop.showAtLocation(tv_plate1,Gravity.BOTTOM,0,-height);
 //        pop.showAtLocation(tv_plate1, Gravity.BOTTOM, 0, 0);
     }*/
    public void hideColor(boolean isHideColor) {
        if (isHideColor) {
            isSelectPlat = true;
            tvTrips.setVisibility(View.GONE);
            rc_carplat_color.setVisibility(View.GONE);
        }else {
            tvTrips.setVisibility(View.VISIBLE);
            rc_carplat_color.setVisibility(View.VISIBLE);
        }
    }
    public void setSelectVehtype(OnSelectVehtypeListener selectVehtype){
        this.selectVehtype = selectVehtype;
        tv_cartype = (TextView) view.findViewById(R.id.tv_cartype);
        ll_cartype = (LinearLayout) view.findViewById(R.id.ll_cartype);
        tv_cartype.setVisibility(View.VISIBLE);
        ll_cartype.setVisibility(View.VISIBLE);
        selectVehtype.onVehtype("1");
    }
    public void setSelectCancle(OnSelectCancleListener selectCancle){
        this.selectCancle = selectCancle;
        selectCancle.onCancle("0");
    }
    public class TransInformation extends ReplacementTransformationMethod {
        /**
         * 原本输入的小写字母
         */
        @Override
        protected char[] getOriginal() {
            return new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        }
        /**
         * 替代为大写字母
         */
        @Override
        protected char[] getReplacement() {
            return new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        }
    }
    long endTime;
    private void backFocus() {
        //博主手机不好，经常点一次却触发两次`onKey`事件，就设置了一个防止多点击，间隔100毫秒。
        long startTime = System.currentTimeMillis();
        tv_confirm.setBackgroundResource(R.color.etcplatcolor);
        EditText editText;
        //循环检测有字符的`editText`，把其置空，并获取焦点。
        for (int i = mEdits.size() - 1; i >= 0; i--) {
            editText = mEdits.get(i);
            if (editText.getText().length() >= 1 && startTime - endTime > 100) {
                editText.setText("");
                editText.setCursorVisible(true);
                keyboardUtil.setEditText(editText);
                if (i == 0){
                    keyboardUtil.changeKeyboard(false);
                }else if(i == 6&&!"使".equals(mEdits.get(0).getText().toString())){
                    keyboardUtil.changKeyboardSpical();
                }else{
                    keyboardUtil.changeKeyboard(true);
                }
                editText.requestFocus();
                setBackground(editText);
                editText.setInputType(InputType.TYPE_NULL);
                hideInputManager(context,editText);
                endTime = startTime;
                return;
            }
        }
    }
    private class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() != 0) {
                keyboardUtil.setHideKeyboardEnable(true);
                keyboardUtil.setDeleteEnable(true);
                if (flagHasPlate) {
                    focus("input");
                }
            } else if (curStatus == STATUS_MODIFY) {
                focus("input");
            }
        }
    }
    public static void hideInputManager(Context context, View view){
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (view !=null && imm != null){
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);  //强制隐藏
        }
    }
    private void focus(String type) {
        EditText editText;
        isPlateInputConfirm = true;
        //利用for循环找出前面还没被输入字符的EditText
        for (int i = 0; i < mEdits.size(); i++) {
            editText = mEdits.get(i);
            if (editText.getText().length() < 1) {//车牌号未输入完成
                if (mEdits.size() == 8 && editText != tv_plate8&&selectEdit!=tv_plate8) {//新能源车牌设置
                    if (TextUtils.isEmpty(tv_plate8.getText().toString())) {
                        if (!isGreenPlat) {
                            delEdit();
                        }
                    }
                }
                isPlateInputConfirm = false;
                setBackground(editText);
                editText.requestFocus();
                if (keyboardUtil == null) {
                    keyboardUtil = new KeyboardUtil(context, editText, view, new KeyboardUtil.DeleteListener() {
                        @Override
                        public void delete(EditText editText) {
                            if (editText == tv_plate8) {
                                if (!isGreenPlat) {
                                    delEdit();
                                }
                            }
                            backFocus();
                        }
                    });
                    keyboardUtil.hideSoftInputMethod();
                    if (!type.equals("click")) {
                        keyboardUtil.showKeyboard();
                    }
                } else {
                    keyboardUtil.setEditText(editText);
                    keyboardUtil.hideSoftInputMethod();
                    if (!type.equals("click")) {
                        keyboardUtil.showKeyboard();
                    }
                }
                String text = mEdits.get(0).getText().toString();
                if (i == 0){
                    keyboardUtil.changeKeyboard(false);
                }else if(i == 6&&!"使".equals(mEdits.get(0).getText().toString())){
                    keyboardUtil.changKeyboardSpical();
                }else{
                    keyboardUtil.changeKeyboard(true);
                }
                return;
            } else {
                editText.setCursorVisible(false);
            }
        }
        if(type.equals("click")&&!flagNew.equals("1")){
            keyboardUtil.showKeyboard();
        }
        if (isPlateInputConfirm) {//所有车牌输入完成
            curStatus = STATUS_COMPLETE;
            setBackground(null);//背景置灰
//            keyboardUtil.setHideKeyboardEnable(true);//可以关闭软键盘
//            keyboardUtil.setDeleteEnable(true);
        }
        //        EditText lastEditText = mEdits.get(mEdits.size() - 1);
        if (isFinish()) {
            //收起软键盘 并不允许编辑 同时将输入的文本提交
            if (isSelectPlat)
                tv_confirm.setBackgroundResource(R.color.main_blue);
            //            lastEditText.setCursorVisible(false);
            /*InputMethodManager imm = (InputMethodManager) getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);*/
            if (type.equals("input"))
                keyboardUtil.hideKeyboard();
        }else {
            tv_confirm.setBackgroundResource(R.color.etcplatcolor);
        }
    }
    public void getResponse() {
        Log.e("CodeView", "ok");
        StringBuilder sb = new StringBuilder();
        //        sb.append(tv_plate1.getText().toString());
        for (int i = 0; i < mEdits.size(); i++) {
            sb.append(mEdits.get(i).getText().toString());
        }
        if(TextUtils.isEmpty(etCode)){
            etCode="";
        }
        String platNumber = sb.toString().toUpperCase();
        if (!RegularUtil.isPlateNum(context,platNumber)){
            ToastUtil.show(context,"您输入的车牌号码输入格式有误");
            return;
        }
        if (!"1".equals(flagNew)) {
            dismiss();
        }
        if (onDatePickerListener != null) {
            onDatePickerListener.onDatePicker(sb.toString(), adapter.getPos(),etCode);
        }
    }
    //对外封装一个重置或直接填写验证码的方法
    public void setText(String text) {
        if (text.length() == mEdits.size()) {
            StringBuilder sb = new StringBuilder(text);
            tv_plate1.setText(sb.substring(0, 1));
            tv_plate2.setText(sb.substring(1, 2));
            tv_plate3.setText(sb.substring(2, 3));
            tv_plate4.setText(sb.substring(3, 4));
            tv_plate5.setText(sb.substring(4, 5));
            tv_plate6.setText(sb.substring(5, 6));
            tv_plate7.setText(sb.substring(6, 7));
            tv_plate8.setText(sb.substring(7, 8));
        } else {
            tv_plate1.setText("");
            tv_plate2.setText("");
            tv_plate3.setText("");
            tv_plate4.setText("");
            tv_plate5.setText("");
            tv_plate6.setText("");
            tv_plate7.setText("");
            tv_plate8.setText("");
            //            first.setCursorVisible(true);
            tv_plate1.requestFocus();
        }
    }
    public void DialogDismiss(){
        dismiss();
    }
    public interface OnDatePickerListener {
        void onDatePicker(String plat, int item, String workCode);
    }
    public interface OnSelectVehtypeListener{
        void onVehtype(String vehtype);
    }
    public interface OnSelectCancleListener{
        void onCancle(String cancle);
    }
    public class PlatColorAdapter extends RecyclerView.Adapter<PlatColorAdapter.VH>{
        private int pos;
        private Context context;
        //② 创建ViewHolder
        public class VH extends RecyclerView.ViewHolder{
            public TextView tv_plat_color;
            public ImageView iv_plat_color;
            public VH(View v) {
                super(v);
                tv_plat_color = (TextView) v.findViewById(R.id.tv_plat_color);
                iv_plat_color = (ImageView) v.findViewById(R.id.iv_plat_color);
            }
        }
        private List<PlateColorMDL> mDatas;
        public PlatColorAdapter(Context context, List<PlateColorMDL> data) {
            this.context = context;
            this.mDatas = data;
        }
        public void setPos(){
            this.pos = -1;
            notifyDataSetChanged();
        }

        public void setPos(int pos) {
            this.pos = pos;
        }

        public int getPos() {
            return pos;
        }
        @Override
        public VH onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_plat_color, parent, false);
            return new VH(v);
        }
        @Override
        public void onBindViewHolder(VH holder, final int position) {
            holder.tv_plat_color.setText(mDatas.get(position).getName());
            int posNew= Integer.parseInt(mDatas.get(position).getDictcode());
            if (posNew== pos&&isSelectPlat)
                setplatColor(holder.tv_plat_color, holder.iv_plat_color, pos);
            else{
//                holder.tv_plat_color.setBackgroundResource(R.mipmap.bg_amount_gray);
                holder.iv_plat_color.setImageDrawable(context.getResources().getDrawable(R.mipmap.bg_amount_gray));
                holder.tv_plat_color.setTextColor(Color.parseColor("#999999"));
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isSelectPlat = true;
                    if("2".equals(mDatas.get(position).getDesc())) {
                        addEdit();
                        isGreenPlat = true;//选中了新能源车牌
                    }
                    else {
                        isGreenPlat = false;//未选中新能源车牌
                        delEdit();
                    }
                    pos = Integer.parseInt(mDatas.get(position).getDictcode());
                    notifyDataSetChanged();
                    if (isFinish())
                        tv_confirm.setBackgroundResource(R.color.main_blue);
                    else
                        tv_confirm.setBackgroundResource(R.color.etcplatcolor);
                }
            });
        }
        @Override
        public int getItemCount() {
            return mDatas.size();
        }
        private void setplatColor(TextView tv, ImageView iv, int position){
            switch (position) {
                case 0:
//                    tv.setBackgroundResource(R.mipmap.bg_plat_color1);
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#FFFFFF"));
                    break;
                case 1:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#333333"));
                    break;
                case 2:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#FFFFFF"));
                    break;
                case 3:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#333333"));
                    break;
                case 4:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#333333"));
                    break;
                case 5:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#333333"));
                    break;
                case 6:
                    Glide.with(context).load(mDatas.get(position).getRemark()).asBitmap()
                            .dontAnimate().placeholder(R.drawable.base_loading).into(iv);
                    tv.setTextColor(Color.parseColor("#333333"));
                    break;
            }
        }
    }
}